<template>
  <div class="bannerlist">
    <!-- 操作栏 -->
    <el-card class="operationcard">
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon>
        添加轮播图
      </el-button>
    </el-card>

    <!-- 轮播图列表 -->
    <el-card class="tablecard">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        style="width: 900px"
        empty-text="暂无数据">
        <el-table-column label="图片" width="200">
          <template #default="{ row }">
            <el-image 
              :src="'http://localhost:9191' + row.img" 
              :preview-src-list="['http://localhost:9191' + row.img]"
              fit="cover"
              style="width: 150px; height: 80px"
            />
          </template>
        </el-table-column>
        <el-table-column prop="goodName" label="商品名称" min-width="200" show-overflow-tooltip />
        <el-table-column prop="showOrder" label="排序" width="100" align="center" />
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button-group>
              <el-button type="primary" link @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" link @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加轮播图' : '编辑轮播图'"
      width="600px">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px">
        <el-form-item label="图片" prop="img">
          <el-upload
            class="bannerupload"
            :action="uploadUrl"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload">
            <el-image
              v-if="form.img"
              :src="'http://localhost:9191' + form.img"
              fit="cover"
              class="upload-image"
            />
            <el-icon v-else class="uploadicon"><Plus /></el-icon>
          </el-upload>
          <div class="uploadtip">建议尺寸：800x400像素，支持jpg、png格式</div>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="form.goodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品ID" prop="goodId">
          <el-input v-model="form.goodId" placeholder="请输入商品ID" />
        </el-form-item>
        <el-form-item label="排序" prop="showOrder">
          <el-input-number v-model="form.showOrder" :min="0" :max="99" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialogfooter">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitLoading">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
// import { Plus,Edit,Delete } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import request from '@/utils/request'

// 状态管理
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const dialogType = ref('add')
const submitLoading = ref(false)
const formRef = ref(null)

// 上传配置
const uploadUrl = 'http://localhost:9191/api/upload'
const uploadHeaders = {
  // 如果需要token等认证信息，在此添加
  // 'Authorization': 'Bearer xxx'
}

// 表单数据
const form = reactive({
  id: '',
  goodId: '',
  goodName: '',
  img: '',
  showOrder: 0
})

// 验证规则
const rules = {
  goodName: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { max: 50, message: '名称最多50个字符', trigger: 'blur' }
  ],
  goodId: [
    { required: true, message: '请输入商品ID', trigger: 'blur' }
  ],
  img: [
    { required: true, message: '请上传轮播图', trigger: 'change' }
  ]
}

// 获取轮播图列表
const getBannerList = async () => {
  loading.value = true
  try {
    const res = await request({
      url: 'http://localhost:9191/api/carousel',
      method: 'get',
      params: {
        page: currentPage.value,
        size: pageSize.value
      }
    })
    
    tableData.value = res.data || []
    total.value = res.total || 0
    
    if (tableData.value.length === 0 && currentPage.value > 1) {
      currentPage.value -= 1
      await getBannerList()
    }
  } catch (error) {
    console.error('获取轮播图列表失败:', error)
    ElMessage.error('获取数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 添加轮播图
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑轮播图
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.assign(form, {
    id: row.id,
    goodId: row.goodId,
    goodName: row.goodName,
    img: row.img,
    showOrder: row.showOrder
  })
  dialogVisible.value = true
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.assign(form, {
    id: '',
    goodId: '',
    goodName: '',
    img: '',
    showOrder: 0
  })
}

// 删除轮播图
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除该轮播图吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await request({
        url: `http://localhost:9191/api/carousel/${row.id}`,
        method: 'delete'
      })
      ElMessage.success('删除成功')
      getBannerList()
    } catch (error) {
      console.error('删除轮播图失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 上传前校验
const beforeUpload = (file) => {
  const isImage = ['image/jpeg', 'image/png'].includes(file.type)
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传jpg/png格式的图片！')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过2MB！')
    return false
  }
  return true
}

// 上传成功回调
const handleUploadSuccess = (res) => {
  if (res.code === 200) {
    form.img = res.data?.img || res.img
    ElMessage.success('上传成功')
  } else {
    ElMessage.error(res.message || '上传失败')
  }
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const requestData = {
          goodId: form.goodId,
          goodName: form.goodName,
          img: form.img,
          showOrder: form.showOrder
        }

        const url = dialogType.value === 'add' 
          ? 'http://localhost:9191/api/carousel' 
          : `http://localhost:9191/api/carousel/${form.id}`
        
        const method = dialogType.value === 'add' ? 'post' : 'put'
        
        await request({
          url,
          method,
          data: requestData
        })
        
        ElMessage.success(dialogType.value === 'add' ? '添加成功' : '修改成功')
        dialogVisible.value = false
        getBannerList()
      } catch (error) {
        console.error('操作失败:', error)
        ElMessage.error(error.response?.data?.message || '操作失败')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getBannerList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getBannerList()
}

// 初始化加载数据
onMounted(() => {
  getBannerList()
})
</script>

<style scoped>
.operationcard {
  margin-bottom: 20px;
}
.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
.bannerupload :deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.bannerupload :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}
.upload-image {
  width: 300px;
  height: 150px;
  display: block;
}
.uploadicon {
  font-size: 28px;
  color: #8c939d;
  width: 300px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.uploadtip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}
</style>